﻿using System;
using System.Diagnostics;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using com.hyrentals.common;

namespace com.hyrentals.webcommon.filter
{
    public class LogActionFilter : ActionFilterAttribute
    {
        private Stopwatch _sw = new Stopwatch();
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _sw.Reset();
            _sw.Start();
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            _sw.Stop();

            string DeviceID = String.Empty;
            HttpCookie cookie = filterContext.HttpContext.Request.Cookies["udid"];
            if (cookie != null)
            {
                DeviceID = cookie.Value;
            }

            Log(string.Format("It takes {0} ms to generate result", _sw.ElapsedMilliseconds),
                filterContext.RouteData,
                filterContext.HttpContext.Request.RawUrl,
                filterContext.HttpContext.Request.UserHostAddress,
                DeviceID
                );
        }


        private void Log(string methodName, RouteData routeData, string url, string UserIp, string DeviceID)
        {
            var controllerName = routeData.Values["controller"];
            var actionName = routeData.Values["action"];
            var message = String.Format("{0}.{1} [{2}] {3} from {4}", controllerName, actionName, methodName, url, UserIp);
            if (!string.IsNullOrEmpty(DeviceID))
            {
                message = String.Format("{0}.{1} [{2}] {3} from {4} udid={5}", controllerName, actionName, methodName, url, UserIp, DeviceID);
            }

            Logger.Info(message);
        }
    }
}
